<template>
  <view class="container" style="background: #FFF;min-height: 100%;">
    <!-- 搜索框 -->
    <uni-search-bar
      placeholder="请输入车牌号"
      @confirm="query()"
      @cancel="cancel"
      cancel-text="取消"
      v-model="searchParam.searchValue">
      <uni-icons slot="searchIcon" color="#999999" size="18" type="home"/>
    </uni-search-bar>

    <uni-segmented-control
      :current="activeTab"
      :values="tabList.map(item => item.label)"
      @clickItem="handleTabClick"
      styleType="text"
      activeColor="#007aff"
    />

    <view v-if="releaseRecordsList.length === 0" style="border-top: 1px solid #dcdcdc">
      <image src="/static/nodata.png" style="width: 100%"></image>
    </view>

    <!-- 渲染存储记录 -->
    <view style="border-top: 1px solid #dcdcdc">
      <uni-card v-for="(item, index) in releaseRecordsList" :key="index"  :title="findById(item.storeId,selectData.storeList)?.storeName" :extra="formatDate(item.createTime)+' 创建'" @click.stop="openReleaserecordsDetail(item.id,'update')">
        <uni-row>
          <uni-col :span="24" style="text-align: left;">存储车牌：{{ item.licensePlate }}</uni-col>
          <uni-col :span="24" style="text-align: left;">联系电话：{{ item.contactNumber }}</uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="12" style="text-align: left;">存储类型：{{ getCodeText(item.storageType,selectData.storageTypeList) }}</uni-col>
          <uni-col :span="12" style="text-align: left;">
            存储状态：
            <uni-tag :text="getCodeText(item.status,selectData.statusList)" :type="getTagType(item.status)" size="mini"/>
          </uni-col>
        </uni-row>

        <uni-row>
          <uni-col :span="24"  style="">
            <view style="padding-top: 5px;width: 100%;display: flex;align-items: center;justify-content: flex-end;">
              <view>
                <button v-if="item.status == '0'" class="mini-btn" type="warn" size="mini" @click.stop="deleteById(item.id)" style="z-index: 2;">删除</button>
              </view>
            </view>
          </uni-col>
        </uni-row>
      </uni-card>
    </view>

    <!-- FAB 按钮 -->
    <uni-fab ref="fab" :horizontal="'right'" :vertical="'bottom'" :direction="'horizontal'" @fabClick="openDepositRecordEnableList()"/>
  </view>
</template>

<script lang="ts">
  import { ReleaseRecordsApi, ReleaseRecordsVO } from '@/sheep/api/releaserecords';
  import { DictUtils } from '@/sheep/store/DictUtils';
  import { StoreApi } from '@/sheep/api/store';
  import { DepositRecordsApi } from '@/sheep/api/depositrecords';

  export default {
    components: {},
    data() {
      return {
        tabList: [
          { status: '', label: '全部' },
          { status: '1', label: '已预约' },
          { status: '2', label: '已接单' },
          { status: '3', label: '已出库' },
          { status: '4', label: '已完成' },
        ],
        selectData:{
          statusList:[],
          storageTypeList:[],
          storeList:[]
        },
        searchParam:{
          pageNo:1,
          searchValue: "",
          status:[],
          storeId:uni.getStorageSync('storeId')
        },
        releaseRecordsList: [] as ReleaseRecordsVO[]
      };
    },
    onLoad: function (options) {
      this.initSelectData();
    },
    onShow() {
      this.query();
    },
    onPullDownRefresh() {
      this.query();
      setTimeout(function () {
        uni.stopPullDownRefresh();
      }, 1000);
    },
    onReachBottom(){
      this.query(++this.searchParam.pageNo);
    },
    methods: {
      handleTabClick(e) {
        this.searchParam.status = this.tabList[e.currentIndex].status;
        this.query();
      },
      // 点击 FAB 按钮时跳转到详情页
      openReleaserecordsDetail(id: string,type: string = "create") {
        // 初始化一个参数对象，id 必须存在
        const params = { type };

        // 如果 id 为空，则不执行跳转
        if (!(!id || id === 'null' || id === 'undefined')) {
          params.id = id
        }

        // 构建查询字符串
        const queryString = Object.entries(params)
          .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
          .join('&');

        // 跳转到目标页面
        uni.navigateTo({
          url: `/pages/releaserecords/releaserecordsDetail?${queryString}`
        });
      },
      openDepositRecordEnableList(){
        uni.navigateTo({
          url: `/pages/depositrecords/components/DepositRecordEnableList`
        });
      },
      // 获取存储记录列表
      async query(pageNo?:number) {
        if(pageNo){
          this.searchParam.pageNo = pageNo;
        }else{
          this.searchParam.pageNo = 1;
        }

        try {
          const { data } = await ReleaseRecordsApi.getReleaseRecordsPage({licensePlate:this.searchParam.searchValue,...this.searchParam});
          const { list } = data;

          // 如果是第一页，直接赋值，否则推入新数据
          if (this.searchParam?.pageNo === 1) {
            this.releaseRecordsList = list;
          } else {
            this.releaseRecordsList.push(...list);
          }
        } catch (error) {
          console.error('Failed to fetch release records:', error);
        }
      },
      // 清空搜索值并重新加载记录
      cancel() {
        this.searchParam.searchValue = "";
        this.query();
      },
      // 格式化时间
      formatDate(date: string) {
        const d = new Date(date);
        return d.toLocaleString(); // 使用本地化字符串格式化时间
      },
      getCodeText(status: string,codeList:[]) {
        const item = codeList.find(item=>item.value==status);
        return item?.label || '未知';
      },
      getTagType(status: number){
        switch (status) {
          case 1:return "primary";
          case 2:return "success";
          case 3:return "warning";
          case 4:return "error";
          default:return "";
        }
      },
      findById(id: string,list:[]):any {
        const item = list.find(item=>item.id==id);
        return item;
      },
      async initSelectData() {
        this.selectData.statusList = DictUtils.getDictData('tire_release_records_status');
        this.selectData.storageTypeList = DictUtils.getDictData('tire_storage_type');

        const storeResult = await StoreApi.getStorePage({});
        this.selectData.storeList = storeResult?.data?.list || [];
      },
      async deleteById(id:number){
        uni.showModal({
          title: '提示',
          content: '是否确认删除？',
          success: async function (res) {
            if (res.confirm) {
              const { code, msg } =  await ReleaseRecordsApi.deleteReleaseRecords(id);
              uni.showToast({
                title: code == "0" ? "删除成功" : msg,
                icon: "none",
              });
              if (code == "0") {
                await this.query()
              }
            }
          }
        });
      }
    }
  };
</script>

<style lang="scss">
  /* 这里可以添加一些样式 */
</style>
